package next.fire.spinus.logx.api;

import next.fire.spinus.logx.api.model.ProviderEnum;

import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by daibing on 2020/9/14.
 */
public class LogServiceFactory {
    private static final ConcurrentMap<ProviderEnum, LogService> IMPL_MAPPING = new ConcurrentHashMap<>(2);

    static {
        ServiceLoader<LogService> serviceLoader = ServiceLoader.load(LogService.class);
        for (LogService logService : serviceLoader) {
            try {
                register(logService);
            } catch (Exception e) {
                // ignore error when load spring bean
            }
        }
    }

    /**
     * 如果实现类是Spring Bean，需要手工注册
     */
    public static void register(LogService logService) {
        ProviderEnum provider = logService.getProvider();
        IMPL_MAPPING.put(provider, logService);
    }

    public static LogService get(ProviderEnum provider) {
        LogService logService = IMPL_MAPPING.get(provider);
        if (logService == null) {
            throw new RuntimeException("Not found logService by provider: " + provider);
        }
        return logService;
    }

}
